<template>
  <div class='container'>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="card">
          <div slot="header" class="clearfix">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          </div>
          <div class="card-body">
            <el-tree
              ref="tree" :props="props" :data="data" :highlight-current="false" node-key="id"
              :default-expand-all="true" :filter-node-method="filterNode" :render-content="renderContent"
            ></el-tree>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="sticky-card">
          <div slot="header" class="clearfix">
            编辑栏目
          </div>
          <div class="card-body">
            <el-form class="form" ref="form" :model="form"
              label-width="120px" :rules="rules"
            >
              <el-form-item label="栏目名称" prop="name">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
              <template v-if="form.isLeaf">
                <el-form-item label="自动审核" prop="autoApproval">
                  <el-select v-model="form.autoApproval" placeholder="请选择">
                    <el-option label="是" :value="0"></el-option>
                    <el-option label="否" :value="1"></el-option>
                  </el-select>
                </el-form-item>
                <template v-if="!form.autoApproval">
                  <el-form-item label="每周自动审核" prop="weekList">
                    <el-select v-model="form.weekList" multiple placeholder="请选择">
                      <el-option
                        v-for="item in weekOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item v-for="(item, index) in form.time"
                    :key="index"
                    :label=" index === 0 ? '每天自动审核':''"
                    :prop="'time'+(index+1)"
                  >
                    <el-time-picker
                      style="width: 100%;"
                      is-range
                      v-model="item.range"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围">
                    </el-time-picker>
                  </el-form-item>

                  <el-form-item v-if="form.time.length < 3">
                    <el-button @click="addTimeRange()" type="success" icon="el-icon-plus" size="mini" plain
                      round>添加一条时间规则
                    </el-button>
                  </el-form-item>
                </template>
              </template>

              <!--<el-form-item v-if="form.isLeaf" label="启用">-->
              <!--<el-select v-model="form.enabled" placeholder="请选择">-->
              <!--<el-option label="是" :value="0"></el-option>-->
              <!--<el-option label="否" :value="1"></el-option>-->
              <!--</el-select>-->
              <!--</el-form-item>-->
              <div style="text-align: center">
                <el-button :disabled="!form.id" @click="handleCancel">取消修改</el-button>
                <el-button :disabled="!form.id" type="primary" @click="edit(form)">确认修改</el-button>
              </div>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="新增" :visible.sync="centerDialogVisible" width="40%" center>
      <el-form :rules="rules" class="form" ref="formCreate" :model="formCreate" label-width="110px">
        <el-form-item label="栏目名称" prop="name">
          <el-input v-model="formCreate.name"></el-input>
        </el-form-item>
        <!--<el-form-item label="自动审核">-->
        <!--<el-select v-model="formCreate.autoApproval" placeholder="请选择">-->
        <!--<el-option label="是" :value="0"></el-option>-->
        <!--<el-option label="否" :value="1"></el-option>-->
        <!--</el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="启用">
          <el-select v-model="formCreate.enabled" placeholder="请选择">
            <el-option label="是" :value="0"></el-option>
            <el-option label="否" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <div style="text-align: center">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="append(nodeInfo.node, nodeInfo.data)">确认</el-button>
        </div>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
  import { listList, listAdd, listPut, listDelete, listEnable, listGetEdit } from '../../api/column'
  import pinyin from 'pinyin'
  import errorLog from '../../store/modules/errorLog'

  export default {
    name: 'columnList',
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        listList({
          pageNum: 1,
          pageSize: 10000
        }).then(response => {
          const temp = {}
          const result = []
          const data = response.Data
          const length = data.length
          for (let i = 0; i < length; i++) {
            temp[data[i].id] = data[i]
          }
          for (let i = 0; i < length; i++) {
            if (temp[data[i].id].parentId && temp[data[i].parentId]) {
              if (!temp[data[i].parentId].children) {
                temp[data[i].parentId].children = []
              }
              temp[data[i].parentId].children.push(temp[data[i].id])
            } else {
              result.push(temp[data[i].id])
            }
          }
          this.data[0].children = result
        })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1 || pinyin(data.name, {
          style: pinyin.STYLE_FIRST_LETTER,
          heteronym: true
        }).join('').indexOf(value) !== -1
      },
      resetForm() {
        this.form = {
          name: '',
          id: '',
          autoApproval: 1,
          enabled: 1,
          isLeaf: false,
          node: {},
          weekList: [],
          time: [{ range: '' }]
        }
        this.$refs['form'].resetFields()
      },
      handleCancel() {
        this.form = Object.assign({}, this.lastForm)
      },
      handleNodeClick(node, data, e) {
        this.$refs['form'].resetFields()
        e.stopPropagation()
        listGetEdit(data).then((response) => {
          const getData = response.Data[0]
          this.form.name = data.name
          this.form.id = data.id
          this.form.isLeaf = node.isLeaf
          this.form.autoApproval = data.autoApproval
          this.form.enabled = data.enabled
          this.form.node = node
          if (getData.auditDayList.length) {
            this.form.weekList = getData.auditDayList
          } else {
            this.form.weekList = []
          }
          if (getData.auditTimeList.length) {
            this.form.time = getData.auditTimeList.sort((a, b) => (a.startTime.hour - b.startTime.hour)).map(e => ({
              range: [
                (new Date()).setHours(e.startTime.hour, e.startTime.minute, e.startTime.second),
                (new Date()).setHours(e.endTime.hour, e.endTime.minute, e.endTime.second)
              ]
            }))
          } else {
            this.form.time = [{ range: '' }]
          }
          this.lastForm = Object.assign({}, this.form)
        })
      },
      handleAppend(node, data, e) {
        e.stopPropagation()
        this.formCreate.name = ''
        this.formCreate.autoApproval = 1
        this.formCreate.enabled = 1
        this.centerDialogVisible = true
        this.nodeInfo.node = node
        this.nodeInfo.data = data
        this.nodeInfo.e = e
        this.$nextTick(() => {
          this.$refs['formCreate'].clearValidate()
        })
      },
      append(node, data, e) {
        const leaf = {
          parentId: data.id,
          name: this.formCreate.name,
          autoApproval: this.formCreate.autoApproval,
          enabled: this.formCreate.enabled
        }
        this.$refs['formCreate'].validate((valid) => {
          if (valid) {
            listAdd(leaf).then((response) => {
              this.centerDialogVisible = false
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              if (!data.children) {
                this.$set(data, 'children', [])
              }
              leaf.id = response.Data[0]
              data.children.push(leaf)
              node.expanded = true
            })
          }
        })
      },
      edit(data) {
        if (!data.id) return
        this.$refs['form'].validate((valid) => {
          if (valid) {
            listPut({
              id: data.id,
              name: data.name,
              enabled: data.enabled,
              autoApproval: data.autoApproval,
              auditDayCrudParamsList: data.weekList.map(e => ({
                cmsNewsClassId: data.id,
                weekOfDay: e
              })),
              auditTimeCrudParamList: data.time.filter(e => !!e.range).map(e => {
                const start = new Date(e.range[0])
                const end = new Date(e.range[1])
                return {
                  cmsNewsClassId: data.id,
                  startTime: {
                    hour: start.getHours(),
                    minute: start.getMinutes(),
                    second: start.getSeconds()
                  },
                  endTime: {
                    hour: end.getHours(),
                    minute: end.getMinutes(),
                    second: end.getSeconds()
                  }
                }
              })
            }).then(() => {
              // this.getList()
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              data.node.data.name = data.name
              data.node.data.autoApproval = data.autoApproval
              data.node.data.enabled = data.enabled
              this.resetForm()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      remove(node, data, e) {
        e.stopPropagation()
        this.$confirm('确认删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          listDelete(data).then(() => {
            const nodes = node.parent.childNodes
            nodes.splice(nodes.indexOf(node), 1)
            if (nodes.length === 0) {
              node.parent.data.child = 0
              node.parent.isLeaf = true
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      start(node, data, e) {
        e.stopPropagation()
        this.$confirm('确认启用', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          data.node = node
          data.enabled = 0
          listEnable({
            id: data.id,
            name: data.name,
            enabled: data.enabled,
            autoApproval: data.autoApproval
          }).then(() => {
            this.getList()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          })
        })
      },
      stop(node, data, e) {
        e.stopPropagation()
        this.$confirm('确认停用', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          data.node = node
          data.enabled = 1
          listEnable({
            id: data.id,
            name: data.name,
            enabled: data.enabled,
            autoApproval: data.autoApproval
          }).then(() => {
            this.getList()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          })
        })
      },
      renderContent(h, { node, data, store }) {
        return (
          <span class={(node.isLeaf && node.level > 1) ? 'custom-tree-node' : 'custom-tree-node custom-tree-notLeaf'}>
            <span>
              <el-tooltip className='item' effect='dark' content={node.label} placement='top-start'>
                <span class='tree-label'>{node.label}&nbsp;</span>
              </el-tooltip>
              {(node.isLeaf && node.level > 1 && !data.autoApproval) ? <el-tag type='primary' size='mini'>自</el-tag> : ''}
              {(node.isLeaf && node.level > 1 && data.enabled) ? <el-tag size='mini' type='warning'>停</el-tag> : ''}
            </span>
            <span>
              {node.level < 4
                ? <el-button size='mini' type='text' on-click={(e) => this.handleAppend(node, data, e)}>新增</el-button>
                : ''}
              {node.isLeaf && node.level > 1
                ? data.enabled
                  ? <el-button size='mini' type='text' on-click={(e) => this.start(node, data, e)}>启用</el-button>
                  : <el-button size='mini' type='text' on-click={(e) => this.stop(node, data, e)}>停止</el-button>
                : ''}
              {node.level > 1
                ? <el-button
                  size='mini' type='text'
                  on-click={(e) => this.handleNodeClick(node, data, e)}
                >编辑</el-button>
                : ''}
            </span>
          </span>)
      },
      addTimeRange() {
        if (this.form.time[this.form.time.length - 1].range[1]) {
          this.form.time.push({
            range: null
          })
        } else {
          this.$message({
            type: 'warning',
            message: '请填入时间后添加'
          })
        }
      }
    },

    data() {
      const validateTimeChoose = (rule, value, callback) => {
        if (this.form.weekList.length || this.form.time[0].range) {
          callback()
        } else {
          callback(new Error('请至少输入每周或每天规则中的一种'))
        }
      }
      const validateTimeRange = (rule, value, callback) => {
        if(this.form.time[rule.param - 1].range){
          if (new Date(this.form.time[rule.param - 1].range[0]) > new Date(this.form.time[rule.param - 2].range[1])) {
            callback()
          } else {
            callback(new Error('请输入上一条规则后的时间段'))
          }
        } else {
          callback()
        }
      }
      return {
        filterText: '',
        centerDialogVisible: false,
        props: {
          label: 'name',
          id: 'id'
        },
        data: [{
          name: '栏目列表',
          id: 0,
          children: []
        }],
        rules: {
          name: [{ required: true, message: '请输入...', trigger: 'change' }],
          autoApproval: [{ required: true, message: '请输入...', trigger: 'change' }],
          weekList: [{ validator: validateTimeChoose, trigger: 'change', param: 0 }],
          time1: [{ validator: validateTimeChoose, trigger: 'change', param: 1 }],
          time2: [{ validator: validateTimeRange, trigger: 'change', param: 2 }],
          time3: [{ validator: validateTimeRange, trigger: 'change', param: 3 }]
        },
        weekOptions: [{
          label: '星期日',
          value: 0
        }, {
          label: '星期一',
          value: 1
        }, {
          label: '星期二',
          value: 2
        }, {
          label: '星期三',
          value: 3
        }, {
          label: '星期四',
          value: 4
        }, {
          label: '星期五',
          value: 5
        }, {
          label: '星期六',
          value: 6
        }],
        form: {
          name: '',
          autoApproval: '',
          enabled: '',
          isLeaf: false,
          weekList: [],
          time: [{
            range: ''
          }]
        },
        lastForm: {},
        formCreate: {
          name: '',
          autoApproval: 1,
          enabled: 1
        },
        nodeInfo: {
          node: {},
          data: {},
          e: {}
        },
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    }
  }
</script>

<style type="scss" scoped>
  .col {
    width: inherit;
  }

  .card-body {
    margin-top: 1rem;
  }

  .form {
    max-width: 500px !important;
    margin: auto !important;
  }
</style>

<style>
  .el-tag {
    margin-right: 3px;
    background-color: rgba(64, 158, 255, .1);
    color: #409EFF;
    border-radius: 4px;
    padding: 0 3px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid rgba(64, 158, 255, .2);
  }

  .el-tag--warning {
    background-color: rgba(230, 162, 60, .1);
    border-color: rgba(230, 162, 60, .2);
    color: #e6a23c;
  }

  .tree-label {
    display: inline-block;
    max-width: 145px;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .el-dialog__header {
    padding: 15px !important;
  }
</style>
